import java.rmi.Remote; 
import java.rmi.RemoteException; 
import java.util.ArrayList;
import java.rmi.Naming;
import java.rmi.server.UnicastRemoteObject;


public class ChatServer extends UnicastRemoteObject implements Chat
{
    private ArrayList<String> nicks;
    private ArrayList<ChatBack> chatBacks;

    public ChatServer() throws RemoteException
    {
	super();
	nicks = new ArrayList();
	this.chatBacks = new ArrayList();
    }
    
    public void connect(String nick,ChatBack ref) throws RemoteException
    {
	nicks.add(nick);
	chatBacks.add(ref);
    }
    
    public void disconnect(String nick, ChatBack ref) throws RemoteException
    {
	int index = nicks.indexOf(nick);
	nicks.remove(index);
	int index2 = chatBacks.indexOf(ref);
	chatBacks.remove(index);
    }

    public void send(String src, String msg) throws RemoteException
    {
	System.out.println("From " + src + " : "+ msg);
	for (ChatBack back : chatBacks)
	    {
		back.send(src,msg);
	    }
    }
    
    public static void main(String args[]){

	if (args.length != 1) {
	    System.out.println("Usage: ChatServer port");
	    System.exit(1);
	}
	
	try { 
	    // Create server and activate Chat object
	    ChatServer obj = new ChatServer(); 
	    
	    // Bind this object to the local RMI registry
	    String port = args[0];
	    String url = "rmi://localhost:" + port + "/Chat"; 	    
	    Naming.rebind(url, obj);
	    
        } catch (Exception e) { 
	    System.out.println("ChatServer Exception: " + e.getMessage()); 
	    e.printStackTrace(); 
        } 


    }
}